import tkinter as tk
from tkinter import ttk, messagebox
import sqlite3
import datetime
import os
from ui_design import MainUI
from auth import LoginUI

def get_software_info():
    """
    获取软件信息
    返回软件信息的字典，供系统使用
    
    Returns:
        dict: 包含软件信息的字典
    """
    try:
        # 连接数据库
        conn = sqlite3.connect('water_electricity.db')
        cursor = conn.cursor()
        
        # 查询软件信息
        cursor.execute("SELECT brand, name, version, designer, email, dev_time FROM software_info WHERE id = 1")
        software_info = cursor.fetchone()
        
        # 关闭数据库连接
        conn.close()
        
        if software_info:
            return {
                'brand': software_info[0] or "",
                'name': software_info[1] or "",
                'version': software_info[2] or "",
                'designer': software_info[3] or "",
                'email': software_info[4] or "",
                'dev_time': software_info[5] or ""
            }
        else:
            # 返回默认值
            return {
                'brand': "",
                'name': "吾已水电费管理系统",
                'version': "v1.5",
                'designer': "",
                'email': "",
                'dev_time': ""
            }
    except Exception as e:
        print(f"获取软件信息时发生错误: {str(e)}")
        # 发生错误时返回默认值
        return {
            'brand': "",
            'name': "吾已水电费管理系统",
            'version': "v1.5",
            'designer': "",
            'email': "",
            'dev_time': ""
        }

class WaterElectricityManager:
    def __init__(self):
        self.root = tk.Tk()
        
        # 获取软件信息
        software_info = get_software_info()
        
        # 构建窗口标题：软件品牌 + 软件名称 + 软件版本
        brand = software_info.get('brand', '')
        name = software_info.get('name', '吾已水电费管理系统')
        version = software_info.get('version', 'v1.5')
        
        # 如果有品牌信息，格式为"品牌名称"，否则直接显示软件名称
        if brand:
            title = f"《{brand}{name}》 {version}"
        else:
            title = f"《{name}》 {version}"
        
        self.root.title(title)
        self.root.geometry("1200x700")
        
        # 初始化数据库
        self.init_database()
        
        # 初始化认证系统
        self.auth = None
        self.ui = None
        
        # 隐藏主窗口，显示登录界面
        self.root.withdraw()
        self.show_login()
        
    def init_database(self):
        """初始化数据库"""
        conn = sqlite3.connect('water_electricity.db')
        cursor = conn.cursor()
        
        # 创建基础信息表
        cursor.execute('''
            CREATE TABLE IF NOT EXISTS properties (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                name TEXT NOT NULL,
                type TEXT NOT NULL,
                area REAL,
                contact_person TEXT,
                contact_phone TEXT,
                status TEXT DEFAULT '正常'
            )
        ''')
        
        # 创建收费标准表
        cursor.execute('''
            CREATE TABLE IF NOT EXISTS price_config (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                property_type TEXT NOT NULL,
                water_price REAL NOT NULL,
                electricity_price REAL NOT NULL,
                effective_date TEXT
            )
        ''')
        
        # 创建用户表
        cursor.execute('''
            CREATE TABLE IF NOT EXISTS users (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                username TEXT NOT NULL UNIQUE,
                password TEXT NOT NULL,
                role TEXT NOT NULL DEFAULT 'user'
            )
        ''')
        
        # 插入默认管理员用户（密码：admin）
        cursor.execute("SELECT COUNT(*) FROM users WHERE username='admin'")
        count = cursor.fetchone()[0]
        if count == 0:
            cursor.execute("INSERT INTO users (username, password, role) VALUES (?, ?, ?)", 
                          ('admin', 'admin', 'admin'))
        
        # 创建抄表记录表
        cursor.execute('''
            CREATE TABLE IF NOT EXISTS meter_readings (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                property_id INTEGER,
                reading_date TEXT,
                water_previous REAL,
                water_current REAL,
                electricity_previous REAL,
                electricity_current REAL,
                water_adjustment REAL DEFAULT 0,
                electricity_adjustment REAL DEFAULT 0,
                water_amount REAL,
                electricity_amount REAL,
                total_amount REAL,
                FOREIGN KEY (property_id) REFERENCES properties (id)
            )
        ''')
        
        # 创建收款记录表
        cursor.execute('''
            CREATE TABLE IF NOT EXISTS payments (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                property_id INTEGER,
                billing_date TEXT,
                payment_date TEXT,
                amount REAL,
                status TEXT,
                payer TEXT,
                notes TEXT,
                FOREIGN KEY (property_id) REFERENCES properties (id)
            )
        ''')
        
        # 插入默认收费标准
        cursor.execute('''
            INSERT OR IGNORE INTO price_config (property_type, water_price, electricity_price, effective_date)
            VALUES 
            ('门面', 6, 1.1, ?),
            ('办公室', 5, 0.9, ?)
        ''', (datetime.datetime.now().strftime("%Y-%m-%d"), datetime.datetime.now().strftime("%Y-%m-%d")))
        
        # 用户表已在上方创建
        # 确保默认管理员用户存在（密码：admin）
        
        conn.commit()
        conn.close()
        
    def show_login(self):
        """显示登录界面"""
        self.auth = LoginUI(self.root, self.on_login_success)
    
    def on_login_success(self):
        """登录成功后的回调函数"""
        self.root.deiconify()  # 显示主窗口
        self.root.state('zoomed')  # 设置窗口最大化
        # 加载主UI
        self.ui = MainUI(self.root, self)
        # 将auth对象传递给UI，用于权限验证
        self.ui.auth = self.auth
        # 更新当前登录用户标签
        if hasattr(self.ui, 'update_current_user_label'):
            self.ui.update_current_user_label()
    
    def run(self):
        """运行程序"""
        self.root.mainloop()

if __name__ == "__main__":
    app = WaterElectricityManager()
    app.run()